Skip to content

ASP.NET Core is a cross-platform, high-performance, open-source framework for building modern web apps using .NET.

Key features:

Rest API

Representational State Transfer (REST) is an architectural style for building web services. REST requests are made over HTTP. They use the same HTTP verbs that web browsers use to retrieve webpages and send data to servers.

Web service APIs that adhere to REST are called RESTful APIs. They are defined as:

  • A base URI.
  • HTTP methods, such as GET, POST, PUT, PATCH, or DELETE.
  • A media type for the data, such as JSON or XML.

Web API Controller

In order to make a controller working, we should extend ControllerBase class in our controller file. Also, we need to decorate the controller with [ApiController] attribute.

Class ControllerBase

A base class for an MVC controller without view support.

This base class provides much standard functionality for handling HTTP requests.

Controller level attributes

  1. [Controller]: Explicitly marks a class as an MVC controller, overriding the default convention of using the "Controller" suffix in the class name.
  2. [ApiController]: Controllers decorated with this attribute are configured with features and behavior building APIs.
  3. [NonController]: Prevents a class from being recognized as a controller, even if it follows the naming convention.
  4. [Route("template")]: Defines a route template for the entire controller, which can then be combined with action-level routes.
  • [Authorize]: Enforces authorization for all actions within the controller, requiring authenticated users to access them.
  • [Consumes("mediaType")]: Specifies the media types (e.g., "application/json") that the controller's actions can consume in requests.
  • [Produces("mediaType")]: Specifies the media types that the controller's actions can produce in responses.

Action-Level Attributes:

  • [HttpGet], [HttpPost], [HttpPut], [HttpDelete], [HttpPatch]: Restricts an action method to handle specific HTTP verbs.
  • [Route("template")]: Defines a specific route template for an individual action, overriding or extending the controller-level route.
  • [FromRoute], [FromQuery], [FromBody], [FromHeader], [FromForm], [FromServices] Specifies the source from which an action parameter's value should be bound (e.g., from the URL route, query string, request body, headers, form data, or dependency injection).
  • [Bind]: Controls which properties of a model should be included or excluded during model binding.
  • [ValidateAntiForgeryToken]: Protects against cross-site request forgery (CSRF) attacks in MVC applications.
  • [AllowAnonymous]: Allows unauthenticated access to a specific action, even if the controller or a parent filter requires authorization.